﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIManager
{
    private static UIManager _instance = null;
    private Dictionary<UIPanelType, string> panelPathDict; // 存储所有面板prefab的路径
    private Dictionary<UIPanelType, BasePanel> panelDict; // 存储所有面板BasePanel组件
    private Stack<BasePanel> panelStack;    // 存储显示的面板 TODO 已加载的还是显示中的？
    private Transform canvasTran;
    private Transform CanvasTran
    {
        get
        {
            if (canvasTran == null)
            {
                canvasTran = GameObject.FindGameObjectWithTag("UIRoot").transform;
            }
            return canvasTran;
        }
    }

    public static UIManager Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new UIManager();
            }
            return _instance;
        }
    }

    private UIManager()
    {
        ParseUIPanelTypeJson();
    }
    [Serializable]
    class UIPanelTypeJson
    {
        public List<UIPanelInfo> infoList = null;
    }
    private void ParseUIPanelTypeJson()
    {
        panelPathDict = new Dictionary<UIPanelType, string>();

        TextAsset ta = Resources.Load<TextAsset>("UIPanelType");
        UIPanelTypeJson jsonObject = JsonUtility.FromJson<UIPanelTypeJson>(ta.text);

        foreach (UIPanelInfo info in jsonObject.infoList)
        {
            panelPathDict.Add(info.panelType, info.path);
        }
    }

    public void PushPanel(UIPanelType panelType)
    {
        if (panelStack == null)
            panelStack = new Stack<BasePanel>();

        if (panelStack.Count > 0)
        {
            BasePanel topPanel = panelStack.Peek();
            topPanel.OnPause();
        }

        BasePanel panel = GetPanel(panelType);
        panel.OnEnter();
        panelStack.Push(panel);
    }
    public void PopPanel()
    {
        if (panelStack == null)
            panelStack = new Stack<BasePanel>();

        if (panelStack.Count <= 0) return;

        BasePanel topPanel = panelStack.Pop();
        topPanel.OnExit();

        if (panelStack.Count <= 0) return;
        BasePanel topPanel2 = panelStack.Peek();
        topPanel2.OnResume();
    }

    private BasePanel GetPanel(UIPanelType panelType)
    {
        if (panelDict == null)
        {
            panelDict = new Dictionary<UIPanelType, BasePanel>();
        }

        BasePanel panel = panelDict.TryGet(panelType);
        if (panel == null)
        {
            // panel为空，则生成panel
            string path = panelPathDict.TryGet(panelType);
            GameObject instPanel = GameObject.Instantiate(Resources.Load(path) as GameObject);
            instPanel.transform.SetParent(CanvasTran, false);
            panel = instPanel.GetComponent<BasePanel>();
            panelDict.Add(panelType, panel);
        }

        return panel;
    }
}
